package codegen

import (
	"fmt"
	"gitee.com/hxchjm/goge/codegen/utils"
	"gitee.com/hxchjm/goge/codegen/utils/pathx"
	"github.com/siddontang/go/config"
	"path/filepath"
	"strings"
)

const clientTemplate = `package api

import (
	"context"
	"fmt"
	"go-main/library/net/rpc/warden"
	"google.golang.org/grpc"
)

// AppID .
const AppID = "TODO: ADD APP ID"

// NewClient new grpc client
func NewClient(cfg *warden.ClientConfig, opts ...grpc.DialOption) ({{.serviceCamelName}}Client, error) {
	client := warden.NewClient(cfg, opts...)
	cc, err := client.Dial(context.Background(), fmt.Sprintf("%s", AppID))
	if err != nil {
		return nil, err
	}
	return New{{.serviceCamelName}}Client(cc), nil
}
`

func genClient(dir, rootPkg string, cfg *config.Config, filename string) error {
	//name := strings.ToLower(api.Service.Name)
	//filename, err := format.FileNamingFormat(cfg.NamingFormat, name)
	//if err != nil {
	//	return err
	//}

	/*	filename := name
		configName := filename
		if strings.HasSuffix(filename, "-api") {
			filename = strings.ReplaceAll(filename, "-api", "")
		}*/
	svrCamelName := utils.SnakeToCamel(filepath.Base(rootPkg))
	return utils.GenFile(utils.FileGenConfig{
		Dir:          dir,
		Subdir:       apiDir,
		Filename:     filename,
		TemplateName: "mainTemplate",
		//Category:        category,
		//TemplateFile:    mainTemplateFile,
		BuiltinTemplate: clientTemplate,
		Data: map[string]string{
			"importPackages":   genClientImports(rootPkg),
			"serviceName":      rootPkg,
			"serviceCamelName": svrCamelName,
		},
	})
}

func genClientImports(parentPkg string) string {
	var imports []string
	imports = append(imports, fmt.Sprintf("\"%s\"", pathx.JoinPackages(parentPkg, appDir)))
	//imports = append(imports, fmt.Sprintf("\"%s/core/conf\"", vars.ProjectOpenSourceURL))
	//imports = append(imports, fmt.Sprintf("\"%s/rest\"", vars.ProjectOpenSourceURL))
	return strings.Join(imports, "\n\t")
}
